<template>
  <div class="my_page_container">
    <q-splitter
      class="bg-white"
      v-model="splitterRatio"
      style="height: 550px"
    >
      <template v-slot:before>
        <div class="row q-pa-xs q-gutter-sm">
          <q-input outlined dense color="base" style="width: 120px">
            <template v-slot:append>
              <q-icon name="search" color="indigo" />
            </template>
          </q-input>
          <q-btn
            dense
            outline
            size="sm"
            color="primary"
            label="刷新"
            icon="refresh"
          />
        </div>
        <q-separator />
        <q-scroll-area style="height: 450px; max-width: 300px">
          <div class="q-pa-sm my-text-overflow">
            <AmyListItem
              :show-list="iconTypeList"
              @update-current-item="onNavListSelected"
            />
          </div>
        </q-scroll-area>
      </template>
      <template v-slot:after>
        <div class="bg-white">
          <AmyQueryItem
            search-label="图标名称"
            @make-search-condition="queryTable"
          />
        </div>
        <div class="bg-white">
          <q-table
            id="my-xls"
            bordered
            flat
            separator="cell"
            :tableTitle= "tableTitle"
            :columns="columns"
            row-key="name"
            :rows="dbFilterList"
            :pagination="dbPagination"
            :rows-per-page-options="[10,20]"
            selection="multiple"
            v-model:selected="selectedItems"
          >

            <!--  插槽：表格头部左侧    -->
            <template v-slot:top-left>
              <q-input
                outlined
                dense
                color="base"
                v-model="filterText"
                :input-style="{ width: '150px'}"
              >
                <template v-slot:append>
                  <q-icon name="search" color="indigo" />
                </template>
              </q-input>
            </template>

            <!--  插槽：表格头部左侧    -->
            <template v-slot:top-right>
              <div class="q-gutter-sm">
                <q-btn
                  dense
                  unelevated
                  color="secondary"
                  label="新增"
                  icon="mdi-comment-plus"
                  @click="addDlgItem"
                />
                <q-btn
                  dense
                  unelevated
                  color="amber"
                  label="导入"
                  icon="mdi-file-import"
                />
                <q-btn
                  dense
                  unelevated
                  color="pink"
                  label="导出"
                  icon="mdi-database-export"
                  @click="exportExcel"
                />
              </div>
            </template>

            <!--  插槽：某个单元格    -->
            <template #body-cell-typeId="props">
              <q-td :props="props">
                {{findCatalogLabel(iconTypeList, props.row.typeId)}}
              </q-td>
            </template>
            <template #body-cell-icon="props">
              <q-td :props="props">
                <q-icon
                  color="deep-orange"
                  :name="props.row.value"
                  size="sm"
                />
              </q-td>
            </template>
            <template #body-cell-operation="props">
              <q-td :props="props">
                <q-btn
                  flat
                  round
                  dense
                  color="primary"
                  icon="edit"
                  @click="editDlgItem(props.rowIndex)"
                >
                  <q-tooltip>编辑</q-tooltip>
                </q-btn>
                <q-btn
                  flat
                  round
                  dense
                  color="negative"
                  icon="mdi-delete-empty"
                  @click="deleteDlgItem(props.rowIndex)"
                >
                  <q-tooltip>删除</q-tooltip>
                </q-btn>
              </q-td>
            </template>

            <!--   底部插槽     -->
            <template v-slot:bottom>
              <AmyPagination :page-msg="dbPagination" @update="refreshTableAry"/>
            </template>
          </q-table>
          <IconDlg
            ref="myAddDlgRef"
            :icon-type-arr="iconTypeList"
            :item-data="getActiveItem()"
            @cancel-icon-item="cancelAddDlg"
            @submit-icon-item="submitAddDlg"
          />

          <AmyDeleteDlg
            ref="myDelDlgRef"
            :selected-index="deletedIndex"
            @btnSubmit="submitDelDlg"
          />
        </div>
      </template>
    </q-splitter>
  </div>
</template>

<script lang="ts">
import { defineAsyncComponent, defineComponent, onMounted, reactive, ref, watch, onUnmounted } from 'vue';
import { useSysCatalogTbl } from '../../../hook/useSysCatalogTbl';
import { sysCatalogType, sysBaseUrlAPI } from '../../../util/SysBaseConst';
import api from 'axios';
import * as XLSX from 'xlsx';
import { useMessageNotify } from 'src/hook/common/useMessageNotify';
import BaseItem from 'pages/BaseItem.vue';
import { EStatusType, ItemType } from 'src/hook/common/useCommonVisitType';
import useCommonVisitDatabase from 'src/hook/common/useCommonVisitDatabase';
import { useCatalogTool } from 'src/hook/common/useCatalogTool';
import { CQueryParam } from 'src/components/basic/basicModel';
import { cataItem } from 'src/hook/common/useCatalogType';

import { IconItem } from './IconModel';


const AmyListItem = defineAsyncComponent(() => import('components/basic/AmyListItem.vue'));
const AmyDeleteDlg = defineAsyncComponent(() => import('components/basic/AmyDeleteDlg.vue'));
const IconDlg = defineAsyncComponent(() => import('./IconDlg.vue'));
export type DeleteDlgInstance = InstanceType<typeof AmyDeleteDlg>;
export type IconDlgInstance = InstanceType<typeof IconDlg>;


export default defineComponent({
  name: 'IconIndex',
  extends: BaseItem,
  components: {
    AmyListItem,
    IconDlg
  },
  setup (props, context) {
    //*********************************************************************************************
    //      splitter
    //*********************************************************************************************
    //分割组件分割比例30%
    let splitterRatio = ref(18);

    //*********************************************************************************************
    //      消息通知
    //*********************************************************************************************
    //消息通知
    const {
      showMessage
    } = useMessageNotify();

    //*********************************************************************************************
    //            列表对应数据
    //*********************************************************************************************
    //选中列表
    let myNavSelectedListItem = ref(0);

    //点击事件
    const onNavListSelected = (r: cataItem) => {
      myNavSelectedListItem.value = r.id;

      //检索条件发生变化
      queryParam.id = myNavSelectedListItem.value;

      //新增记录分类修改
      state.itemData.typeId = myNavSelectedListItem.value;

      //查询部门，有条件查询
      loadList();
    }

    //*********************************************************************************************
    //      查询模块
    //*********************************************************************************************
    //查询输入参数
    let queryParam = reactive({
      id: 0,
      name: '',
      startDate: '',
      endDate: ''
    });

    //有条件查询
    const queryTable = (s: CQueryParam) => {
      queryParam.name = s.name;
      queryParam.startDate = s.startDate;
      queryParam.endDate = s.endDate;

      //有条件查询
      loadList();
    }


    //*********************************************************************************************
    //      读取表格数据
    //*********************************************************************************************
    //检索响应数据
    const state = reactive({
      itemData: {
        id: 0,
        typeId: 0,
        label: '',
        value: '',
        sortCode: '',
        description: '',
        createTime: '',
        createUserId: 0,
        updateTime: '',
        updateUserId: 0
      }
    });

    //查询数据库
    const fetchApi = () => {
      return api.post(sysBaseUrlAPI.SYS_ICON_API_PAGE, {
        typeId: queryParam.id,
        name: queryParam.name,
        startDate: queryParam.startDate,
        endDate: queryParam.endDate,
        pageNum: dbPagination.value.pageNum,
        pageSize: dbPagination.value.pageSize
      });
    };

    //删除记录
    const deleteApi = (item: ItemType) => {
      return api.post(sysBaseUrlAPI.SYS_ICON_API_DELETE, { id: item.id });
    };

    //增加记录
    const confirmAddApi = (item: ItemType) => {
      return api.post(sysBaseUrlAPI.SYS_ICON_API_ADD, {
        id: item.id,
        typeId: item.typeId,
        label: item.label,
        value: item.value,
        sortCode: item.sortCode,
        createTime: '',
        createUserId: 0,
        updateTime: '',
        updateUserId: 0
      });
    };

    //修改记录
    const confirmEditApi = (item: ItemType) => {
      return api.post(sysBaseUrlAPI.SYS_ICON_API_UPDATE, {
        id: item.id,
        typeId: item.typeId,
        label: item.label,
        value: item.value,
        sortCode: item.sortCode,
        createTime: '',
        createUserId: 0,
        updateTime: '',
        updateUserId: 0
      });
    };

    const {
      dbList,
      dbFilterList,
      dbPagination,
      dbCurrentIndex,
      dbStatus,
      getActiveItem,
      filterList,
      loadList,
      addItem,
      editItem,
      deleteItem,
      cancelItem,
      confirmApi
    } = useCommonVisitDatabase(state.itemData, fetchApi, confirmAddApi, confirmEditApi, deleteApi);

    //*********************************************************************************************
    //      读取目录
    //*********************************************************************************************
    const {
      findCatalogLabel,
      findCatalogId
    } = useCatalogTool();

    const {
      iconTypeList,
      getCatalog,
      removeCatalog
    } = useSysCatalogTbl();

    //*********************************************************************************************
    //      表格
    //*********************************************************************************************
    const columns = [
      {
        name: 'id',
        required: true,
        label: 'ID号',
        align: 'center',
        field: (row:any) => (row.id),
        sortable: true
      },
      { name: 'typeId', align: 'center', label: '分类', field: 'typeId' },
      { name: 'label', align: 'center', label: '名称', field: 'label' },
      { name: 'value', align: 'center', label: '键值', field: 'value' },
      { name: 'icon', align: 'center', label: '图标', field: 'icon' },
      { name: 'sortCode', align: 'center', label: '序码', field: 'sortCode' },
      { name: 'operation', align: 'center', label: '操作', field: 'operation' }
    ];

    //rows
    const tableTitle = ref('图标数据');
    let selectedItems = ref([]);
    let filterText = ref('');
    let myDelDlgRef = ref<DeleteDlgInstance|null>(null);
    let myAddDlgRef = ref<IconDlgInstance|null>(null);
    let deletedIndex = ref(0);

    //检索显示
    const searchTableAry = () => {
      filterList(filterText.value);
    }

    //添加用户
    const addDlgItem = () => {
      if (myAddDlgRef.value) {
        addItem();
        myAddDlgRef.value.show('新建图标');
      }
    }

    //编辑用户
    const editDlgItem = (row: number) => {
      if (myAddDlgRef.value) {
        editItem(row);
        myAddDlgRef.value.show('编辑图标');
      }
    }

    //删除用户
    const deleteDlgItem = (row: number) => {
      if (myDelDlgRef.value) {
        deletedIndex.value = row;
        myDelDlgRef.value.show('图标信息');
      }
    }

    //更新分页组件
    const refreshTableAry = (pageNum: number) => {
      dbPagination.value.pageNum = pageNum;
      loadList();
    }

    //导出excel
    const exportExcel = () => {
      let workbook = XLSX.utils.table_to_book(document.getElementById('my-xls')); //需要在table上定义一个id
      try {
        XLSX.writeFile(workbook, 'BOX信息.xlsx');
      } catch (e) {
        showMessage('导出失败,失败信息:!');
      }
    }

    //*********************************************************************************************
    //      增加、修改模块
    //*********************************************************************************************
    //取消添加
    const cancelAddDlg = () => {
      //判断是增加还是修改
      if (dbStatus.value === EStatusType.ADD_TYPE) {
        cancelItem(0);
      }
    }

    //新建提交
    const submitAddDlg = (item: IconItem) => {
      console.log(item);
      confirmApi(item);
      loadList();
    }

    //*********************************************************************************************
    //      删除确认模块
    //*********************************************************************************************
    //提交确认对话框
    const submitDelDlg = (index: number) => {
      deleteItem(index);
    }

    //*********************************************************************************************
    //      启动模块
    //*********************************************************************************************
    //初始化
    const init = () => {
      //表格数据,无条件
      loadList();

      //目录
      getCatalog(sysCatalogType.ICON_TYPE_CODE);
    }

    //监视检索框
    watch(filterText, () => {
      searchTableAry();
    });

    onMounted(() => {
      init();
    });

    onUnmounted(() => {
      removeCatalog(sysCatalogType.ICON_TYPE_CODE);
    });

    return {
      splitterRatio,
      onNavListSelected,
      queryTable,

      findCatalogLabel,
      findCatalogId,
      iconTypeList,

      columns,
      tableTitle,
      selectedItems,
      filterText,
      deletedIndex,
      myDelDlgRef,
      myAddDlgRef,
      searchTableAry,
      addDlgItem,
      editDlgItem,
      deleteDlgItem,
      refreshTableAry,

      dbList,
      dbFilterList,
      dbPagination,
      dbCurrentIndex,
      getActiveItem,

      cancelAddDlg,
      submitAddDlg,
      submitDelDlg,

      exportExcel
    }
  }
})
</script>

<style lang="scss" sortCoded>
.my_input {
  width: 150px;
}
</style>
